package com.gopay.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @author ddh02
 * @IPV4Util
 * @2017/8/21 9:46  www.gopay.com.cn Inc.All rights reserved.
 */


public class IPV4Util {

    private static Logger logger = LoggerFactory.getLogger(IPV4Util.class);

    public static String getIpv4() {

        try {

            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface current = interfaces.nextElement();
                if (!current.isUp() || current.isLoopback() || current.isVirtual()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = current.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress addr = addresses.nextElement();
                    if (addr.isLoopbackAddress()) {
                        continue;
                    }

                    if (addr instanceof Inet4Address) {
                        return addr.getHostAddress();
                    }
                }
            }

        } catch (Exception e) {
            logger.error("获取本地ip地址错误：", e);
        }
        return "error";
    }

    public static void main(String[] args) {
        System.out.println(getIpv4());
    }
}
